package com.aotain.oframework.converter;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

public abstract class DTOConverter<PO, DTO> {

	public abstract PO toPO(DTO dto);

	public abstract DTO toDTO(PO po);

	public List<DTO> toDTOs(Collection<PO> poL) {
		if (poL == null || poL.size() == 0) {
			return new ArrayList<DTO>();
		}
		List<DTO> dtoL = new ArrayList<DTO>();
		for (PO po : poL) {
			dtoL.add(toDTO(po));
		}
		return dtoL;
	}

	public List<PO> toPOs(Collection<DTO> dtoL) {
		if (dtoL == null || dtoL.size() == 0) {
			return new ArrayList<PO>();
		}
		List<PO> poL = new ArrayList<PO>();
		for (DTO dto : dtoL) {
			poL.add(toPO(dto));
		}
		return poL;
	}

	public Page<DTO> toDTOs(Page<PO> poPage, int pageNumber) {
		if (poPage == null) {
			return null;
		}
		Page<DTO> dtoPage = new PageImpl<DTO>(
				this.toDTOs(poPage.getContent()),
				new PageRequest(pageNumber, poPage.getSize(), poPage.getSort()),
				poPage.getTotalElements());
		return dtoPage;
	}

	public Page<DTO> toDTOs(Page<PO> poPage) {
		return this.toDTOs(poPage, poPage.getNumber());
	}
}
